﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using System.Data.Common;

namespace DataAccess
{
    public class ContactDAL
    {
        private static readonly string SQL_GETALL = "select * from contacts";

        public static List<Contact> GetAll()
        {
            List<Contact> list = new List<Contact>();
            var command = SqlHelper.GetCommand(SQL_GETALL);
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                list.Add(Build(reader));
            }
            return list;
        }

        private static Contact Build(DbDataReader reader)
        {
            Contact contact = new Contact();

            contact.BatchGrayData = SqlHelper.GetNullableString(reader["Batch_Gray_Data"]);
            contact.CardSource = SqlHelper.GetNullableValue<long>(reader["Card_Source"]);
            contact.CloudTaskID = SqlHelper.GetNullableString(reader["Cloud_Task_ID"]);
            contact.CreatedDate = SqlHelper.GetTimeSpanFromNullableLong(reader["Created_Date"]);
            contact.HypercardID = SqlHelper.GetNullableString(reader["Hypercard_ID"]);
            contact.HypercardTimestamp = SqlHelper.GetTimeSpanFromNullableLong(reader["Hypercard_Timestamp"]);
            contact.HypercardUpdated = SqlHelper.GetNullableValue<long>(reader["Hypercard_Updated"]);
            contact.HypercardUpdateMsgID = SqlHelper.GetNullableString(reader["hypercard__update_msgid"]);
            contact.ID = (long)reader["_id"];
            contact.LastModifiedTime = SqlHelper.GetTimeSpanFromNullableLong(reader["Last_Modified_Time"]);
            contact.LocalCloudState = SqlHelper.GetNullableValue<long>(reader["Local_Cloud_State"]);
            contact.RecognizeState = SqlHelper.GetNullableValue<long>(reader["Recognize_State"]);
            contact.SortComapnyPinyin = SqlHelper.GetNullableString(reader["Sort_Comapny_Pinyin"]);
            contact.SortNamePinyin = SqlHelper.GetNullableString(reader["Sort_Name_Pinyin"]);
            contact.SyncAccountID = SqlHelper.GetNullableValue<long>(reader["Sync_Account_ID"]);
            contact.SyncCID = SqlHelper.GetNullableString(reader["Sync_CID"]);
            contact.SyncExtraState = SqlHelper.GetNullableValue<long>(reader["Sync_Extra_State"]);
            contact.SyncRevision = SqlHelper.GetNullableValue<long>(reader["Sync_Revision"]);
            contact.SyncSourceID = SqlHelper.GetNullableString(reader["Sync_Source_ID"]);
            contact.SyncState = SqlHelper.GetNullableValue<long>(reader["Sync_State"]);
            contact.SyncTimestamp = SqlHelper.GetNullableValue<long>(reader["Sync_Timestamp"]);
            contact.SysContactID = SqlHelper.GetNullableString(reader["Sys_Contact_ID"]);

            return contact;
        }
    }
}
